/**
 * 用户状态管理
 * 使用 Pinia 管理用户登录状态和信息
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { mockUserInfo } from '@/mock/data.js'

export const useUserStore = defineStore('user', () => {
  // 员工信息
  const employeeInfo = ref({})

  // 功能列表
  const funcList = ref([])

  // 菜单列表
  const menuList = ref([])

  // 初始化选项
  const init_option = ref({})

  // 公告数据
  const notice = ref([])

  // 消息相关状态
  const c1 = ref('0')
  const c2 = ref('0')
  const status = ref('0')

  // 计算属性：登录状态（基于 employee_info 是否存在）
  const isLoggedIn = computed(() => {
    return employeeInfo.value !== undefined &&
      employeeInfo.value !== null &&
      Object.keys(employeeInfo.value).length > 0
  })

  /**
   * 简单存储数据到 localStorage（Mock模式不需要加密）
   * @param {string} key - 存储键
   * @param {any} value - 存储值
   */
  const saveToStorage = (key, value) => {
    localStorage.setItem(key, JSON.stringify(value))
  }

  /**
   * 从 localStorage 读取数据（Mock模式不需要解密）
   * @param {string} key - 存储键
   * @param {any} defaultValue - 默认值
   * @returns {any} 存储的数据
   */
  const loadFromStorage = (key, defaultValue) => {
    try {
      const stored = localStorage.getItem(key)
      if (!stored) return defaultValue
      return JSON.parse(stored)
    } catch (error) {
      console.error(`读取 ${key} 失败:`, error)
      return defaultValue
    }
  }

  /**
   * 处理数据清理的情况
   * 清理所有缓存并跳转到登录页
   */
  const handleDataClear = () => {
    try {
      console.warn('正在清理所有本地缓存...')

      // 清理所有localStorage
      localStorage.clear()

      // 清理所有sessionStorage
      sessionStorage.clear()

      // 重置所有状态
      employeeInfo.value = {}
      funcList.value = []
      menuList.value = []
      init_option.value = {}
      c1.value = 0
      c2.value = 0
      status.value = '0'

      // 延迟跳转，确保清理完成
      setTimeout(() => {
        window.location.href = '/login'
      }, 100)

    } catch (error) {
      console.error('清理缓存失败:', error)
      // 如果清理失败，强制刷新页面
      window.location.reload()
    }
  }

  /**
   * 设置用户信息
   * @param {Object} info - 用户信息
   */
  const setUserInfo = (info) => {
    employeeInfo.value = info.employee_info || {}
    funcList.value = info.func_list || []
    menuList.value = info.menu_list || []
    init_option.value = info.init_option || {}
    notice.value = info.notice || mockUserInfo.notice || []

    // 批量保存到 localStorage
    saveToStorage('employeeInfo', employeeInfo.value)
    saveToStorage('funcList', funcList.value)
    saveToStorage('menuList', menuList.value)
    saveToStorage('init_option', init_option.value)
    saveToStorage('notice', notice.value)
  }

  /**
   * 清除用户信息
   */
  const clearUserInfo = () => {
    // 清除所有状态
    employeeInfo.value = {}
    funcList.value = []
    menuList.value = []
    init_option.value = {}
    notice.value = []
    c1.value = 0
    c2.value = 0
    status.value = '0'

    // 清除 localStorage
    localStorage.clear();
  }

  /**
   * 从 localStorage 恢复用户信息或使用Mock数据
   */
  const restoreUserInfo = () => {
    try {
      // 尝试从localStorage恢复，如果没有则使用Mock数据
      const storedEmployeeInfo = loadFromStorage('employeeInfo', null)
      const storedFuncList = loadFromStorage('funcList', null)
      const storedMenuList = loadFromStorage('menuList', null)
      const storedInitOption = loadFromStorage('init_option', null)


      if (storedEmployeeInfo && storedFuncList && storedMenuList && storedInitOption) {
        // 使用存储的数据
        employeeInfo.value = storedEmployeeInfo
        funcList.value = storedFuncList
        menuList.value = storedMenuList
        init_option.value = storedInitOption
        // 总是使用Mock数据中的notice，确保数据是最新的
        notice.value = mockUserInfo.notice
        // 重新保存notice数据
        saveToStorage('notice', notice.value)
      } else {
        // 使用Mock数据
        employeeInfo.value = mockUserInfo.employee_info
        funcList.value = mockUserInfo.func_list
        menuList.value = mockUserInfo.menu_list
        init_option.value = mockUserInfo.init_option
        notice.value = mockUserInfo.notice

        // 保存Mock数据到localStorage
        saveToStorage('employeeInfo', employeeInfo.value)
        saveToStorage('funcList', funcList.value)
        saveToStorage('menuList', menuList.value)
        saveToStorage('init_option', init_option.value)
        saveToStorage('notice', notice.value)
      }
    } catch (error) {
      console.error('恢复用户信息失败，使用Mock数据:', error)
      // 如果恢复失败，使用Mock数据
      employeeInfo.value = mockUserInfo.employee_info
      funcList.value = mockUserInfo.func_list
      menuList.value = mockUserInfo.menu_list
      init_option.value = mockUserInfo.init_option
      notice.value = mockUserInfo.notice
    }
  }

  /**
   * 更新用户信息
   * @param {Object} updates - 要更新的字段
   */
  const updateUserInfo = (updates) => {
    if (employeeInfo.value) {
      // 更新员工信息
      if (updates.employee_info !== undefined) {
        employeeInfo.value = updates.employee_info
        saveToStorage('employeeInfo', employeeInfo.value)
      }

      // 更新功能列表
      if (updates.func_list !== undefined) {
        funcList.value = updates.func_list
        saveToStorage('funcList', funcList.value)
      }

      // 更新菜单列表
      if (updates.menu_list !== undefined) {
        menuList.value = updates.menu_list
        saveToStorage('menuList', menuList.value)
      }

      // 更新初始化选项
      if (updates.init_option !== undefined) {
        init_option.value = updates.init_option
        saveToStorage('init_option', init_option.value)
      }
    }
  }

  /**
   * 更新消息状态
   * @param {Object} msgData - 消息数据 {c1, c2, status}
   */
  const updateMsgStatus = (msgData) => {
    if (msgData.c1 !== undefined) c1.value = msgData.c1
    if (msgData.c2 !== undefined) c2.value = msgData.c2
    if (msgData.status !== undefined) status.value = msgData.status
  }

  /**
   * 生成动态路由
   * @param {Array} menuList - 菜单列表
   * @returns {Array} 路由配置数组
   */
  const generateRoutes = (menuList) => {
    if (!menuList?.length) return []

    const createRoute = (menu) => {
      const route = {
        path: menu.path || `/${menu.id}`,
        name: menu.name || menu.title,
        component: () => import(`@/views/${menu.component || 'index'}.vue`),
        meta: {
          title: menu.title,
          icon: menu.icon,
          requiresAuth: true,
          menuId: menu.id
        }
      }

      if (menu.children?.length) {
        route.children = menu.children.map(createRoute)
      }

      return route
    }

    return menuList.map(createRoute)
  }

  /**
   * 获取动态路由
   * @returns {Array} 动态路由配置
   */
  const getDynamicRoutes = () => generateRoutes(menuList.value)

  return {
    // 状态
    isLoggedIn,
    employeeInfo,
    funcList,
    menuList,
    init_option,
    notice,
    c1,
    c2,
    status,

    // 方法
    setUserInfo,
    clearUserInfo,
    restoreUserInfo,
    updateUserInfo,
    updateMsgStatus,
    generateRoutes,
    getDynamicRoutes,
    handleDataClear
  }
})
